<?php
if (!defined('ABSPATH')) { exit; }

// 获取安全模块实例检查许可证状态
$security = wp_spider_premium_security();
$is_premium = $security->is_premium_activated();
?>

<div class="spa-container">
    <!-- 侧边导航栏 -->
    <nav class="spider-nav-sidebar">
        <div class="spider-nav-header">
            <h1 class="spider-nav-title">蜘蛛分析</h1>
        </div>
        
        <ul class="spider-nav-menu">
            <li class="spider-nav-item">
                <a href="#overview" class="spider-nav-link active" data-route="overview">
                    <span class="nav-icon">📊</span>
                    蜘蛛概况
                </a>
            </li>
            <li class="spider-nav-item">
                <a href="#logs" class="spider-nav-link" data-route="logs">
                    <span class="nav-icon">📝</span>
                    蜘蛛日志
                </a>
            </li>
            <li class="spider-nav-item">
                <a href="#list" class="spider-nav-link" data-route="list">
                    <span class="nav-icon">📋</span>
                    蜘蛛列表
                </a>
            </li>
            <li class="spider-nav-item">
                <a href="#paths" class="spider-nav-link" data-route="paths">
                    <span class="nav-icon">🛤️</span>
                    访问路径
                </a>
            </li>
            <li class="spider-nav-item">
                <a href="#articles" class="spider-nav-link" data-route="articles">
                    <span class="nav-icon">📄</span>
                    文章爬取
                </a>
            </li>
            <li class="spider-nav-item">
                <a href="#indexing" class="spider-nav-link" data-route="indexing">
                    <span class="nav-icon">🔍</span>
                    收录分析
                </a>
            </li>
            <li class="spider-nav-item">
                <a href="#push" class="spider-nav-link" data-route="push">
                    <span class="nav-icon">🚀</span>
                    搜索引擎推送
                </a>
            </li>
            <li class="spider-nav-item">
                <a href="#settings" class="spider-nav-link" data-route="settings">
                    <span class="nav-icon">⚙️</span>
                    设置
                </a>
            </li>
            <li class="spider-nav-item">
                <a href="#plugin-settings" class="spider-nav-link" data-route="plugin-settings">
                    <span class="nav-icon">🔧</span>
                    插件设置
                </a>
            </li>
        </ul>
        
        <!-- PRO版本升级链接 -->
        <div class="spider-nav-pro">
            <a href="<?php echo admin_url('admin.php?page=spider-license'); ?>" class="spider-nav-link" target="_blank">
                升级PRO版
            </a>
        </div>
        
        <!-- 广告位区域 -->
        <div class="spider-nav-ads" id="spider-nav-ads">
            <!-- 广告位将通过API动态加载 -->
        </div>
    </nav>
    
    <!-- 主内容区域 -->
    <main class="spider-content-area" id="spider-content-area">
        <!-- 初始加载状态 -->
        <div class="spa-loading">
            <div class="loading-spinner"></div>
            <p>正在加载蜘蛛分析...</p>
        </div>
    </main>
</div>

<!-- 插件内部底部标志 -->
<div class="spider-footer">
    <div class="spider-footer-content">
        <a href="https://zibovip.top" target="_blank" class="spider-footer-logo">
            <span class="logo-text">小Z</span>
        </a>
    </div>
</div>

<style>
/* 导航图标样式 */
.nav-icon {
    display: inline-block;
    width: 20px;
    text-align: center;
    margin-right: 8px;
    font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .spa-container {
        flex-direction: column;
    }
    
    .spider-nav-sidebar {
        width: 100%;
        height: auto;
        position: relative;
        padding: 10px 0;
    }
    
    .spider-content-area {
        margin-left: 0;
        padding: 15px;
    }
    
    .spider-nav-menu {
        display: flex;
        flex-wrap: wrap;
        gap: 5px;
        padding: 0 10px;
    }
    
    .spider-nav-item {
        flex: 1;
        min-width: calc(50% - 5px);
    }
    
    .spider-nav-link {
        padding: 8px 12px;
        font-size: 14px;
        text-align: center;
        border-radius: 4px;
        border-left: none;
        border-bottom: 3px solid transparent;
    }
    
    .spider-nav-link.active {
        border-left: none;
        border-bottom-color: #0073aa;
    }
    
    .spider-nav-link.active::after {
        display: none;
    }
    
    .nav-icon {
        display: block;
        margin: 0 0 4px 0;
        font-size: 18px;
    }
}

/* 深色主题支持 */
@media (prefers-color-scheme: dark) {
    .spider-nav-sidebar {
        background: #1e1e1e;
    }
    
    .spider-content-area {
        background: #2c2c2c;
        color: #fff;
    }
}

/* 侧边栏广告位样式 */
.spider-nav-ads {
    margin-top: auto;
    padding: 20px;
    border-top: 1px solid #3c434a;
}

.spider-nav-ads .ad-item {
    background: rgba(255,255,255,0.05);
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 10px;
    text-align: center;
    transition: all 0.3s ease;
}

.spider-nav-ads .ad-item:hover {
    background: rgba(255,255,255,0.1);
    transform: translateY(-2px);
}

.spider-nav-ads .ad-item img {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
}

.spider-nav-ads .ad-item .ad-title {
    color: #fff;
    font-size: 12px;
    margin: 8px 0 4px;
    font-weight: 500;
}

.spider-nav-ads .ad-item .ad-desc {
    color: #ccc;
    font-size: 10px;
    line-height: 1.4;
}

.spider-nav-ads .ad-loading,
.spider-nav-ads .ad-no-content {
    color: #999;
    font-size: 12px;
    text-align: center;
    padding: 20px;
    font-style: italic;
}

.spider-nav-ads .ad-loading {
    animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
}

/* 页面底部标志样式 */
.spider-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(35, 40, 45, 0.95);
    backdrop-filter: blur(10px);
    border-top: 1px solid #3c434a;
    z-index: 999;
    padding: 10px 0;
}

.spider-footer-content {
    display: flex;
    justify-content: center;
    align-items: center;
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
}

.spider-footer-logo {
    display: inline-flex;
    align-items: center;
    text-decoration: none;
    color: #fff;
    font-weight: 600;
    font-size: 14px;
    transition: all 0.3s ease;
    padding: 8px 16px;
    border-radius: 20px;
    background: linear-gradient(135deg, #0073aa, #005a87);
    box-shadow: 0 2px 8px rgba(0,115,170,0.3);
}

.spider-footer-logo:hover {
    color: #fff;
    text-decoration: none;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,115,170,0.4);
}

.spider-footer-logo .logo-text {
    position: relative;
}

.spider-footer-logo .logo-text::before {
    content: "⚡";
    margin-right: 6px;
    font-size: 16px;
}

/* 调整主内容区域底部边距，避免被底部标志遮挡 */
.spider-content-area {
    padding-bottom: 60px;
}

/* 打印样式 */
@media print {
    .spider-nav-sidebar {
        display: none;
    }
    
    .spider-content-area {
        margin-left: 0;
        padding: 0;
    }
    
    .spider-footer {
        display: none;
    }
}
</style>

<script>
// SPA初始化
jQuery(document).ready(function($) {
    'use strict';
    
    // 确保ajaxurl变量存在
    if (typeof ajaxurl === 'undefined') {
        window.ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    }
    
    console.log('SPA主页面初始化开始');
    console.log('ajaxurl:', window.ajaxurl);
    console.log('wpSpiderMonitor:', typeof wpSpiderMonitor !== 'undefined' ? wpSpiderMonitor : '未定义');
    
    // 预加载所有路由（可选）
    // window.SpiderSPARouter.preloadAllRoutes();
    
    // 添加键盘导航支持
    $(document).on('keydown', function(e) {
        // Alt + 数字键快速导航
        if (e.altKey && e.key >= '1' && e.key <= '9') {
            e.preventDefault();
            const routes = ['#overview', '#logs', '#list', '#paths', '#articles', '#indexing', '#push', '#settings', '#plugin-settings'];
            const index = parseInt(e.key) - 1;
            if (routes[index]) {
                window.SpiderSPARouter.navigateTo(routes[index]);
            }
        }
    });
    
    // 添加面包屑导航（可选）
    function updateBreadcrumb(route) {
        const breadcrumb = $('.spider-breadcrumb');
        if (breadcrumb.length === 0) {
            $('.spider-content-area').prepend('<nav class="spider-breadcrumb" aria-label="面包屑导航"></nav>');
        }
        
        $('.spider-breadcrumb').html(`
            <a href="#overview">蜘蛛分析</a> 
            <span class="separator">></span> 
            <span class="current">${route.title}</span>
        `);
    }
    
    // 监听路由变化
    window.addEventListener('spiderPageLoaded', function(event) {
        const route = event.detail.route;
        if (route) {
            updateBreadcrumb(route);
            
            // 更新页面标题
            document.title = `${route.title} - 蜘蛛分析`;
            
            // 发送页面浏览统计（可选）
            if (typeof gtag !== 'undefined') {
                gtag('event', 'page_view', {
                    page_title: route.title,
                    page_location: window.location.href
                });
            }
        }
    });
    
    // 添加返回顶部按钮
    function addBackToTopButton() {
        if ($('#back-to-top').length === 0) {
            $('body').append(`
                <button id="back-to-top" class="back-to-top" title="返回顶部" style="
                    position: fixed;
                    bottom: 20px;
                    right: 20px;
                    width: 50px;
                    height: 50px;
                    background: #0073aa;
                    color: white;
                    border: none;
                    border-radius: 50%;
                    cursor: pointer;
                    display: none;
                    z-index: 1000;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
                    transition: all 0.3s ease;
                ">
                    ↑
                </button>
            `);
            
            $('#back-to-top').on('click', function() {
                $('html, body').animate({scrollTop: 0}, 500);
            });
            
            $(window).on('scroll', function() {
                if ($(this).scrollTop() > 300) {
                    $('#back-to-top').fadeIn();
                } else {
                    $('#back-to-top').fadeOut();
                }
            });
        }
    }
    
    addBackToTopButton();
    
    // 加载侧边栏广告
    loadSidebarAds();
    
    console.log('SPA 主页面初始化完成');
});

// 加载侧边栏广告位
function loadSidebarAds() {
    const adsContainer = jQuery('#spider-nav-ads');
    if (adsContainer.length === 0) return;
    
    // 显示加载状态
    adsContainer.html('<div class="ad-loading">加载广告中...</div>');
    
    // 从API获取广告数据
    jQuery.post(ajaxurl, {
        action: 'spider_get_ads_data',
        nonce: wpSpiderMonitor.nonce
    })
    .done(function(response) {
        if (response.success && response.data) {
            renderAds(response.data);
        } else {
            // 如果API失败，显示默认广告
            renderDefaultAds();
        }
    })
    .fail(function() {
        console.warn('获取广告数据失败，显示默认广告');
        renderDefaultAds();
    });
    
    function renderAds(ads) {
        // 过滤活跃的广告
        const activeAds = ads.filter(ad => ad.active);
        
        if (activeAds.length === 0) {
            adsContainer.html('<div class="ad-no-content">暂无广告</div>');
            return;
        }
        
        // 渲染广告
        let adsHTML = '';
        activeAds.forEach(ad => {
            adsHTML += `
                <div class="ad-item" data-ad-id="${ad.id}">
                    <a href="${ad.link}" target="${ad.target}" style="text-decoration: none; color: inherit;">
                        <img src="${ad.image}" alt="${ad.title}" loading="lazy" onerror="this.src='https://via.placeholder.com/200x100/666666/ffffff?text=广告图片'">
                        <div class="ad-title">${ad.title}</div>
                        <div class="ad-desc">${ad.description}</div>
                    </a>
                </div>
            `;
        });
        
        adsContainer.html(adsHTML);
        bindAdClickEvents();
        console.log('侧边栏广告加载完成，共', activeAds.length, '个广告');
    }
    
    function renderDefaultAds() {
        // 默认广告数据
        const defaultAds = [
            {
                id: 'ad-default-1',
                title: 'WordPress优化服务',
                description: '专业WordPress网站优化',
                image: 'https://via.placeholder.com/200x100/0073aa/ffffff?text=WordPress+优化',
                link: 'https://zibovip.top',
                target: '_blank'
            },
            {
                id: 'ad-default-2', 
                title: 'SEO工具推荐',
                description: '提升网站搜索排名',
                image: 'https://via.placeholder.com/200x100/28a745/ffffff?text=SEO+工具',
                link: 'https://zibovip.top',
                target: '_blank'
            }
        ];
        
        renderAds(defaultAds);
    }
    
    function bindAdClickEvents() {
        // 添加广告点击统计
        adsContainer.off('click.ad-tracking').on('click.ad-tracking', '.ad-item a', function(e) {
            const adId = jQuery(this).closest('.ad-item').data('ad-id');
            console.log('广告点击:', adId);
            
            // 发送广告点击统计到服务器
            jQuery.post(ajaxurl, {
                action: 'spider_track_ad_click',
                ad_id: adId,
                nonce: wpSpiderMonitor.nonce
            }).fail(function() {
                console.warn('广告点击统计发送失败');
            });
        });
    }
}
</script>
